#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
主窗口模块
应用程序的主界面实现
"""

from PyQt5.QtWidgets import (
    QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, 
    QPushButton, QFileDialog, QLabel, QStatusBar,
    QProgressBar, QMessageBox, QTabWidget
)
from PyQt5.QtCore import Qt, QThread, pyqtSignal
from PyQt5.QtGui import QIcon, QFont
import os

from excel_handler.excel_processor import ExcelProcessor
from data_processor.data_handler import DataHandler
from utils.logger import get_logger

# 获取日志记录器
logger = get_logger(__name__)

class ProcessingThread(QThread):
    """后台处理线程"""
    
    # 信号定义
    progress = pyqtSignal(int)
    status = pyqtSignal(str)
    finished = pyqtSignal(bool, str)
    
    def __init__(self, input_file, output_file, config):
        """
        初始化处理线程
        
        Args:
            input_file (str): 输入文件路径
            output_file (str): 输出文件路径
            config (dict): 配置字典
        """
        super().__init__()
        self.input_file = input_file
        self.output_file = output_file
        self.config = config
        self.is_running = True
    
    def run(self):
        """线程运行方法"""
        try:
            # 更新状态
            self.status.emit("正在加载Excel文件...")
            self.progress.emit(10)
            
            # 创建Excel处理器和数据处理器
            excel_processor = ExcelProcessor()
            data_handler = DataHandler(self.config)
            
            # 读取输入文件
            data = excel_processor.read_excel(self.input_file)
            if data is None:
                raise Exception("无法读取Excel文件")
            
            self.status.emit("正在处理数据...")
            self.progress.emit(30)
            
            # 处理数据
            processed_data = data_handler.process(data, progress_callback=self._update_progress)
            
            self.status.emit("正在保存结果...")
            self.progress.emit(80)
            
            # 保存结果
            success = excel_processor.write_excel(processed_data, self.output_file)
            
            if success:
                self.status.emit("处理完成")
                self.progress.emit(100)
                self.finished.emit(True, "处理成功完成")
            else:
                raise Exception("保存结果失败")
                
        except Exception as e:
            error_msg = f"处理过程中出错: {str(e)}"
            logger.error(error_msg)
            self.status.emit("处理失败")
            self.finished.emit(False, error_msg)
    
    def _update_progress(self, value):
        """更新进度回调函数"""
        # 将数据处理进度映射到整体进度的30%-80%之间
        mapped_progress = 30 + (value / 100) * 50
        self.progress.emit(int(mapped_progress))
    
    def stop(self):
        """停止线程执行"""
        self.is_running = False
        self.wait()

class MainWindow(QMainWindow):
    """应用程序主窗口"""
    
    def __init__(self, config):
        """
        初始化主窗口
        
        Args:
            config (dict): 配置字典
        """
        super().__init__()
        self.config = config
        self.input_file = ""
        self.output_file = ""
        self.processing_thread = None
        
        # 初始化UI
        self.init_ui()
    
    def init_ui(self):
        """初始化用户界面"""
        # 设置窗口属性
        self.setWindowTitle("瀚越包装方案匹配工具")
        self.setGeometry(100, 100, 900, 600)
        
        # 创建中心部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 创建主布局
        main_layout = QVBoxLayout(central_widget)
        
        # 创建选项卡控件
        self.tab_widget = QTabWidget()
        
        # 创建主处理选项卡
        self.create_main_tab()
        
        # 添加选项卡到控件
        self.tab_widget.addTab(self.main_tab, "主处理")
        self.tab_widget.addTab(QWidget(), "配置")
        self.tab_widget.addTab(QWidget(), "帮助")
        
        # 添加选项卡控件到主布局
        main_layout.addWidget(self.tab_widget)
        
        # 创建状态栏
        self.status_bar = QStatusBar()
        self.setStatusBar(self.status_bar)
        
        # 添加进度条到状态栏
        self.progress_bar = QProgressBar()
        self.progress_bar.setMaximumWidth(200)
        self.progress_bar.setVisible(False)
        self.status_bar.addPermanentWidget(self.progress_bar)
        
        # 更新状态
        self.status_bar.showMessage("就绪")
    
    def create_main_tab(self):
        """创建主处理选项卡"""
        self.main_tab = QWidget()
        layout = QVBoxLayout(self.main_tab)
        
        # 文件选择区域
        file_section = QWidget()
        file_layout = QVBoxLayout(file_section)
        
        # 输入文件选择
        input_layout = QHBoxLayout()
        input_layout.addWidget(QLabel("输入文件:"))
        self.input_file_label = QLabel("未选择文件")
        self.input_file_label.setStyleSheet("color: gray;")
        input_layout.addWidget(self.input_file_label, 1)
        self.select_input_btn = QPushButton("浏览...")
        self.select_input_btn.clicked.connect(self.select_input_file)
        input_layout.addWidget(self.select_input_btn)
        file_layout.addLayout(input_layout)
        
        # 输出文件选择
        output_layout = QHBoxLayout()
        output_layout.addWidget(QLabel("输出文件:"))
        self.output_file_label = QLabel("未选择文件")
        self.output_file_label.setStyleSheet("color: gray;")
        output_layout.addWidget(self.output_file_label, 1)
        self.select_output_btn = QPushButton("浏览...")
        self.select_output_btn.clicked.connect(self.select_output_file)
        output_layout.addWidget(self.select_output_btn)
        file_layout.addLayout(output_layout)
        
        # 添加文件选择区域到布局
        layout.addWidget(file_section)
        
        # 处理按钮
        button_layout = QHBoxLayout()
        button_layout.addStretch(1)
        self.process_btn = QPushButton("开始处理")
        self.process_btn.clicked.connect(self.start_processing)
        self.process_btn.setEnabled(False)
        button_layout.addWidget(self.process_btn)
        self.cancel_btn = QPushButton("取消")
        self.cancel_btn.clicked.connect(self.cancel_processing)
        self.cancel_btn.setEnabled(False)
        button_layout.addWidget(self.cancel_btn)
        button_layout.addStretch(1)
        
        layout.addLayout(button_layout)
        layout.addStretch(1)
    
    def select_input_file(self):
        """选择输入文件"""
        last_dir = self.config.get('paths', {}).get('last_input_dir', '')
        file_path, _ = QFileDialog.getOpenFileName(
            self, "选择输入Excel文件", last_dir, "Excel Files (*.xlsx *.xls)"
        )
        
        if file_path:
            self.input_file = file_path
            self.input_file_label.setText(os.path.basename(file_path))
            self.input_file_label.setStyleSheet("color: black;")
            
            # 更新配置中的最后输入目录
            self.config.setdefault('paths', {})['last_input_dir'] = os.path.dirname(file_path)
            
            # 如果未选择输出文件，自动生成输出文件路径
            if not self.output_file:
                base_name = os.path.splitext(file_path)[0]
                self.output_file = f"{base_name}_processed.xlsx"
                self.output_file_label.setText(os.path.basename(self.output_file))
                self.output_file_label.setStyleSheet("color: black;")
            
            # 启用处理按钮
            self.process_btn.setEnabled(True)
    
    def select_output_file(self):
        """选择输出文件"""
        last_dir = self.config.get('paths', {}).get('last_output_dir', '')
        
        # 如果有输入文件，使用相同目录作为默认目录
        if self.input_file:
            default_dir = os.path.dirname(self.input_file)
            default_filename = os.path.splitext(os.path.basename(self.input_file))[0] + "_processed.xlsx"
            default_path = os.path.join(default_dir, default_filename)
        else:
            default_dir = last_dir
            default_path = ""
        
        file_path, _ = QFileDialog.getSaveFileName(
            self, "保存输出Excel文件", default_path, "Excel Files (*.xlsx)"
        )
        
        if file_path:
            # 确保文件扩展名是.xlsx
            if not file_path.lower().endswith('.xlsx'):
                file_path += '.xlsx'
            
            self.output_file = file_path
            self.output_file_label.setText(os.path.basename(file_path))
            self.output_file_label.setStyleSheet("color: black;")
            
            # 更新配置中的最后输出目录
            self.config.setdefault('paths', {})['last_output_dir'] = os.path.dirname(file_path)
            
            # 启用处理按钮
            if self.input_file:
                self.process_btn.setEnabled(True)
    
    def start_processing(self):
        """开始处理文件"""
        # 检查文件是否存在
        if not os.path.exists(self.input_file):
            QMessageBox.warning(self, "文件错误", "输入文件不存在")
            return
        
        # 禁用按钮
        self.process_btn.setEnabled(False)
        self.select_input_btn.setEnabled(False)
        self.select_output_btn.setEnabled(False)
        self.cancel_btn.setEnabled(True)
        
        # 显示进度条
        self.progress_bar.setVisible(True)
        self.progress_bar.setValue(0)
        
        # 创建并启动处理线程
        self.processing_thread = ProcessingThread(self.input_file, self.output_file, self.config)
        self.processing_thread.progress.connect(self.progress_bar.setValue)
        self.processing_thread.status.connect(self.status_bar.showMessage)
        self.processing_thread.finished.connect(self.processing_finished)
        self.processing_thread.start()
    
    def cancel_processing(self):
        """取消处理"""
        if self.processing_thread and self.processing_thread.isRunning():
            self.status_bar.showMessage("正在取消处理...")
            self.processing_thread.stop()
            self.reset_ui_state()
    
    def processing_finished(self, success, message):
        """处理完成回调"""
        # 显示结果消息
        if success:
            QMessageBox.information(self, "处理成功", f"文件处理成功完成！\n{message}")
        else:
            QMessageBox.critical(self, "处理失败", message)
        
        # 重置UI状态
        self.reset_ui_state()
    
    def reset_ui_state(self):
        """重置UI状态"""
        self.process_btn.setEnabled(True)
        self.select_input_btn.setEnabled(True)
        self.select_output_btn.setEnabled(True)
        self.cancel_btn.setEnabled(False)
        self.progress_bar.setVisible(False)
        self.status_bar.showMessage("就绪")
    
    def closeEvent(self, event):
        """窗口关闭事件"""
        # 检查是否有处理线程在运行
        if self.processing_thread and self.processing_thread.isRunning():
            reply = QMessageBox.question(
                self, "确认退出", 
                "有处理任务正在进行中，确定要退出吗？",
                QMessageBox.Yes | QMessageBox.No, QMessageBox.No
            )
            
            if reply == QMessageBox.Yes:
                self.processing_thread.stop()
                event.accept()
            else:
                event.ignore()
        else:
            event.accept()